package com.fancy.recommendation.exception;

import com.fancy.common.dto.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 推荐服务全局异常处理器
 *
 * @author fancy
 */
@Slf4j
@RestControllerAdvice
public class RecommendationExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleValidationException(MethodArgumentNotValidException e) {
        log.warn("参数校验失败", e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.fail("参数校验失败: " + message);
    }

    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException e) {
        log.warn("参数绑定失败", e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.fail("参数绑定失败: " + message);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
        log.warn("约束违规异常", e);
        return Result.fail("参数校验失败");
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result<Void> handleIllegalArgumentException(IllegalArgumentException e) {
        log.warn("非法参数异常", e);
        return Result.fail("参数错误: " + e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        log.error("系统异常", e);
        return Result.fail("系统异常，请稍后重试");
    }
}
